<template>
  <el-menu-item index="1" @click="handleClick">
    实时路况
    <el-tooltip
      effect="dark"
      content="颜色说明：蓝色-畅通 | 绿色-基本畅通 | 黄色-缓行 | 红色-拥堵"
      placement="right"
    >
      <el-icon class="tip-icon">
        <Warning />
      </el-icon>
    </el-tooltip>
  </el-menu-item>
</template>

<script setup>
import { ref, watch, onBeforeUnmount } from 'vue'
import { useMapStore } from '@/stores/mapStore'
import { ElMessage } from 'element-plus'
import { Warning } from '@element-plus/icons-vue'
import { getAllDataByLayerIndex } from '@/api/mapgis-api/getAllDataByLayerIndex'

const mapStore = useMapStore()
const isActive = ref(false)
const source = ref(null)
const layer = ref(null)

// 样式配置
const TRAFFIC_LEVELS = {
  high: { color: [28, 126, 255], width: 10 }, // 蓝色
  medium: { color: [76, 175, 80], width: 10 }, // 绿色
  low: { color: [255, 235, 59], width: 10 }, // 黄色
  congested: { color: [244, 67, 54], width: 10 }, // 红色
}

// 初始化数据源和图层
watch(
  () => mapStore.mapInstance,
  (map) => {
    if (map) {
      // 创建数据源和图层
      source.value = new window.ol.source.Vector()
      layer.value = new window.ol.layer.Vector({
        source: source.value,
        style: createTrafficStyle(),
        zIndex: 9998,
      })

      // 加载路网数据
      getAllDataByLayerIndex(1)
        .then((features) => {
          source.value.addFeatures(features)
          console.log('路网数据加载成功')
        })
        .catch((error) => {
          ElMessage.error('路网数据加载失败')
          console.error('加载错误:', error)
        })
    }
  },
  { immediate: true },
)

// 动态创建样式函数
function createTrafficStyle() {
  return function (feature) {
    const flow = feature.getProperties().values_['车流量'] // 从 values_ 字段中提取属性
    let level = 'high'
    if (flow > 1800) level = 'congested'
    else if (flow > 1500) level = 'low'
    else if (flow > 1000) level = 'medium'

    return new window.ol.style.Style({
      stroke: new window.ol.style.Stroke({
        color: [...TRAFFIC_LEVELS[level].color, 0.8],
        width: TRAFFIC_LEVELS[level].width,
      }),
    })
  }
}

// 切换图层可见性
const handleClick = () => {
  isActive.value = !isActive.value

  const map = mapStore.mapInstance
  if (map && layer.value) {
    if (isActive.value) {
      map.addLayer(layer.value)
    } else {
      map.removeLayer(layer.value)
    }
  }
  console.log()
}

// 组件卸载时清理
onBeforeUnmount(() => {
  const map = mapStore.mapInstance
  // 清理图层
  if (map && layer.value) {
    map.removeLayer(layer.value)
    layer.value.dispose()
  }
  // 清理数据源
  if (source.value) {
    source.value.clear()
    source.value.dispose()
  }
})
</script>

<style lang="scss" scoped>
.tip-icon {
  margin-left: 8px;
  transition: color 0.3s;

  &:hover {
    color: #409eff;
  }
}
</style>
